﻿using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Pay.Distribution.Controllers
{
    public class TopicController : GeneralController {

        private ITopicService _iTopicService;
        private IMerchantService _iMerchantService;
        public TopicController(ITopicService iTopicService, IMerchantService iMerchantService) {
            _iTopicService = iTopicService;
            _iMerchantService = iMerchantService;
        }

        //获取专题列表
        [HttpGet]
        public JsonResult Gets(TopicQuery query) {
            query.merchant_id = currentUser.user_id;
            var result =  _iTopicService.GetTopics(query);
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }

        public JsonResult Get(int id) {
            var result =  _iTopicService.GetTopic(id);
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }


        [AcceptVerbs(HttpVerbs.Post | HttpVerbs.Put)]
        [ValidateInput(false)]
        public JsonResult Save(topic_model model) {
            var merchant = _iMerchantService.Get(currentUser.user_id);
            var apiResult = UploadList("topic", merchant.merchant_no);
            if (model.id > 0) {
                if (apiResult != null) {
                    int count = 0;
                    for (int i = 0; i<model.topic_groups.Count; i++) {
                        count = i;
                        if (model.topic_groups[i].show_images == null)
                            model.topic_groups[i].show_images = apiResult[i-count];
                    }
                }
            } 
            else {
                if (apiResult != null) {
                    model.show_images = apiResult[1];
                    model.banner = apiResult[0];
                    for (int i = 0; i < model.topic_groups.Count; i++) {
                        if (apiResult.Count > 2) {
                            if (apiResult[2] != null)
                                model.topic_groups[i].show_images = apiResult[i + 2];
                        }
                    }
                }
            }
            model.remark = "";
            model.bind_no =_iMerchantService.Get(currentUser.user_id).merchant_no;
            var result =  _iTopicService.Save(model);
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }

        [HttpDelete]
        public JsonResult Delete(long id) {
            var result = _iTopicService.DeleteTopic(id);
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }
    }
}